// GIF 工具类封装
import Jimp from 'jimp';

// 创建优化的 canvas context
const createOptimizedContext = (width, height) => {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  return canvas.getContext('2d', { willReadFrequently: true });
};

// gif.worker.js 的内容
export const gifWorkerContent = `
(function(global) {
  var ByteArray = function() {
    this.data = [];
  };

  ByteArray.prototype.writeByte = function(val) {
    this.data.push(val & 0xFF);
  };

  // ... 其他 ByteArray 方法 ...

  var GIFEncoder = function() {
    this.width = null;
    this.height = null;
    this.frames = [];
    this.quality = 10;
    this.repeat = 0;
    this.delay = 500;
    this.pixels = null;
    this.indexedPixels = null;
    this.colorTab = null;
    this.colorDepth = 8;
    this.usedEntry = new Array();
    this.palSize = 7;
    this.dispose = -1;
    this.firstFrame = true;
    this.sample = 10;
    this.out = new ByteArray();
  };

  // ... 其他 GIFEncoder 方法 ...

  global.onmessage = function(evt) {
    var data = evt.data;
    try {
      var encoder = new GIFEncoder();
      encoder.setSize(data.width, data.height);
      encoder.setQuality(data.quality);
      encoder.setDelay(data.delay);
      encoder.writeHeader();
      
      data.frames.forEach(function(frame) {
        encoder.addFrame(frame);
      });
      
      encoder.finish();
      
      global.postMessage({
        type: 'finished',
        data: encoder.out.data
      });
    } catch (e) {
      global.postMessage({
        type: 'error',
        message: e.message
      });
    }
  };
})(this);`

// 获取 GIF worker URL
export const getGifWorker = () => {
  const blob = new Blob([gifWorkerContent], { type: 'application/javascript' })
  return URL.createObjectURL(blob)
}

// 创建 GIF 实例
export const createGif = (options = {}) => {
  const defaultOptions = {
    workers: 2,
    quality: 10,
    width: 800,
    height: 600,
    workerScript: getGifWorker(),
    workerTimeout: 30000  // 30秒超时
  }

  return new GIF({
    ...defaultOptions,
    ...options
  })
}

// 将 Canvas 元素添加到 GIF
export const addCanvasToGif = (gif, canvas, options = {}) => {
  const defaultFrameOptions = {
    delay: 1000,
    copy: true
  }
  
  gif.addFrame(canvas, { ...defaultFrameOptions, ...options })
}

// 生成并下载 GIF
export const generateAndDownloadGif = (gif, filename = 'animation.gif') => {
  return new Promise((resolve, reject) => {
    // 添加超时处理
    const timeout = setTimeout(() => {
      gif.abort();
      reject(new Error('GIF generation timeout'));
    }, 30000); // 30秒超时

    gif.on('finished', (blob) => {
      clearTimeout(timeout);
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
      
      // 清理
      URL.revokeObjectURL(url)
      gif.abort()
      
      resolve(blob)
    })

    gif.on('error', (error) => {
      clearTimeout(timeout);
      reject(error);
    });

    gif.render()
  })
}

// 优化的图片处理函数
export const processImage = async (img, width, height) => {
  const ctx = createOptimizedContext(width, height);
  
  // 清空canvas
  ctx.fillStyle = '#FFFFFF';
  ctx.fillRect(0, 0, width, height);

  // 计算缩放比例和位置，保持宽高比
  const scale = Math.min(
    width / img.width,
    height / img.height
  );
  const x = (width - img.width * scale) / 2;
  const y = (height - img.height * scale) / 2;

  // 绘制图片
  ctx.drawImage(
    img,
    x, y,
    img.width * scale,
    img.height * scale
  );

  return ctx.canvas;
}

// 创建 GIF 图片
export const createGifFromImages = async (images, options = {}) => {
  const {
    width = 400,
    height = 300,
    quality = 60,
    delay = 500
  } = options;

  try {
    // 处理所有图片
    const frames = await Promise.all(
      images.map(async (imagePath) => {
        // 读取图片
        const image = await Jimp.read(imagePath);
        
        // 调整尺寸（保持宽高比）
        image.scaleToFit(width, height);
        
        // 创建白色背景
        const background = new Jimp(width, height, 0xFFFFFFFF);
        
        // 将图片居中放置在白色背景上
        const x = (width - image.getWidth()) / 2;
        const y = (height - image.getHeight()) / 2;
        background.composite(image, x, y);

        return {
          frame: background,
          delay
        };
      })
    );

    // 创建 GIF
    const firstFrame = frames[0].frame;
    const buffer = await firstFrame.getBufferAsync(Jimp.MIME_GIF);
    
    // 将 buffer 转换为 Blob
    const blob = new Blob([buffer], { type: 'image/gif' });
    return URL.createObjectURL(blob);

  } catch (error) {
    console.error('GIF 生成失败:', error);
    throw error;
  }
};

// 保存 GIF 到文件
export const saveGifToFile = async (gifBlob, filename) => {
  try {
    // 创建下载链接
    const a = document.createElement('a');
    a.href = gifBlob;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    
    return true;
  } catch (error) {
    console.error('保存 GIF 失败:', error);
    throw error;
  }
}; 